package com.bw.home

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ToastUtils
import com.bw.home.databinding.ActivityRegisterBinding
import com.bw.home.intent.LoginIntent
import com.bw.home.state.LoginState
import com.bw.home.viewmodel.LoginViewModel
import com.bw.lib_common.ConstValue
import com.bw.lib_mvi.BaseActivity
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch


@Route(path = ConstValue.REGISTER)
class RegisterActivity : BaseActivity() {
    lateinit var binding: ActivityRegisterBinding
    lateinit var viewModel: LoginViewModel

    override fun getRootLayout(): View {
        binding = ActivityRegisterBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        super.initView()
        viewModel = ViewModelProvider(this).get(LoginViewModel::class.java)
    }

    override fun initData() {
        super.initData()
        //注册
        binding.registerBt.setOnClickListener {
            goRegister()
        }
    }

    private fun goRegister() {
        lifecycleScope.launch {
            viewModel.intents.send(
                LoginIntent.register(
                    binding.registerUsernameEt.text.toString(),
                    binding.registerPasswordEt.text.toString()
                )
            )
        }
    }

    override fun initEvent() {
        super.initEvent()
        lifecycleScope.launch {
            viewModel.state.collect {
                when (it) {

                    is LoginState.register -> {
                        ToastUtils.showLong("注册成功")
                        finish()
                    }

                    is LoginState.Failed -> {
                        Log.d("TagA", "注册失败: $it")
                    }

                    else -> {}
                }
            }
        }
    }

}